argss <- commandArgs(trailingOnly = TRUE)

print(argss)

dataa <- argss[1]
# name <- argss[2]
# print(dataa)

# names=read.table(name, col.names=c("file", "legend", "win", "sample"), stringsAsFactors=F)
# print(names)

dat=read.table(dataa)
len=nrow(dat)


# names=names[order(names$win),]
# names$legend=strsplit(names$file, '[.]')[[1]][2] #[.]


xlim=c(0, 1)
ylim=xlim
hlineby=.1
hline=seq((ylim[1]+hlineby), (ylim[2]-hlineby), hlineby)
vline=hline

out_name=paste(dataa, 'lorenz.pdf', sep='.')

pdf(out_name, width=8, height=8)

par(ann=F, xaxs='i', yaxs='i')

plot(NA, type='n', xlim=xlim, ylim=ylim, cex.axis=.5)

abline(0,1, col='black')

abline(v=vline, h=hline, lty=3, col='gray')

title_main=paste("Lorenz curves for ", dataa)

title(main=title_main, xlab="Cumulative fraction of genome", ylab="Cumulative fraction of total reads")

# names$color=rainbow(nrow(names))

max_num=10000

simu=runif(max_num)
num_sub=round(max_num/10)
count=hist(simu, breaks=num_sub, plot=F)$counts
rc=sort(count)
rc=c(0, rc)
num_sub=num_sub+1 # start from (0,0)
x=seq(from=0, to=1, length.out=num_sub)
sum=sum(rc)
rc_norm=NULL
for (ii in 1:num_sub) {
	rc_norm[ii]=sum(rc[1:ii]) / sum
}

gini_simu=1-((2*sum(rc_norm)-rc_norm[1]-rc_norm[num_sub])/(num_sub-1))
gini_simu_str=paste('simu', sprintf("%.4f", gini_simu), sep=' ')

lines(x, rc_norm, col='gray')


rc=dat$V1
rc=sort(rc)
rc=c(0, rc)
rc_sum=sum(rc)
len=len+1
rc_norm=NULL
for (ii in 1:len) {
	rc_norm[ii]=sum(rc[1:ii]) / rc_sum
}
x=seq(from=0, to=1, length.out=len)
lines(x, rc_norm, col='blue')

gini=1-((2*sum(rc_norm)-rc_norm[1]-rc_norm[len])/(len-1))
gini_str=paste(dataa, sprintf("%.4f", gini), sep=' ')

# gini_str=vector('character')

# for (i in 1:nrow(names)) {
	# rc0=read.table(names[i,1])
	# if (max_num < nrow(rc0)) {
		# rc=sample(rc0$V1, max_num)
		# len=max_num
	# }else {
		# rc=rc0$V1
		# len=length(rc)
	# }
	
	# rc=sort(rc)
	
	# sum=sum(rc)
	# rc_norm=NULL
	# for (ii in 1:len) {
		# rc_norm[ii]=sum(rc[1:ii]) / sum
	# }
	# x=seq(from=0, to=1, length.out=len)
	# lines(x, rc_norm, col=names$color[i])
	
	# gini=1-((2*sum(rc_norm)-rc_norm[1]-rc_norm[len])/(len-1))
	# gini_str[i]=paste(names$legend[i], sprintf("%.4f", gini), sep=' ')
	
# }

legend("topleft", inset=.05, lty=c(1,1,1), c(gini_str, gini_simu_str), col=c('blue', 'gray'))


dev.off()


